package nlog

import (
	"elflog/common/config"
	"github.com/sirupsen/logrus"
	"os"
)

type NLog struct {
	*logrus.Entry
}

func NewLogger(cfg *config.Config) *NLog {
	var Log = logrus.NewEntry(logrus.New())
	Log.Logger.SetFormatter(&logrus.TextFormatter{})
	level, err := logrus.ParseLevel(cfg.LogLevel)
	if err != nil {
		level = 4 // info
	}
	Log.Logger.SetLevel(level)
	Log.Logger.SetOutput(os.Stdout)
	Log = Log.WithField("trace_id", "")
	Log.Infoln("log init ok")
	log := &NLog{Log}
	log.SetUpLogFile(cfg.LogFile)
	return log
}

func (nlog *NLog) SetUpLogFile(f string) {
	if f == "" || f == "stdout" {
		nlog.Logger.SetOutput(os.Stdout)
		nlog.Logger.Warnln("set log out file to stdout")
		return
	}
	file, e := os.OpenFile(f, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModeAppend)
	if e != nil {
		panic(e)
		return
	}
	nlog.Logger.SetOutput(file)
	nlog.Logger.Warnln("set log out file to " + f)
}

func (log *NLog) WithField(key string, value interface{}) *NLog {
	return &NLog{Entry: log.Entry.WithField(key, value)}
}
